from flask_sqlalchemy import SQLAlchemy

db = SQLAlchemy()


class BaseModelMixin:

    def save_or_update(self):
        db.session.add(self)
        db.session.commit()

    def delete(self):
        db.session.delete(self)
        db.session.commit()


class Dept(BaseModelMixin, db.Model):
    __tablename__ = 'tb_dept'

    no = db.Column('dno', db.Integer, primary_key=True)
    name = db.Column('dname', db.String(10), nullable=False)
    loc = db.Column('dloc', db.String(20), nullable=False)

    emps = db.relationship('Emp', backref='dept', passive_deletes=True)

    def to_dict(self):
        return {
            'no': self.no,
            'name': self.name,
            'loc': self.loc
        }


class Emp(BaseModelMixin, db.Model):
    __tablename__ = 'tb_emp'

    no = db.Column('eno', db.Integer, primary_key=True)
    name = db.Column('ename', db.String(20), nullable=False)
    job = db.Column(db.String(20), nullable=False)
    mgr = db.Column(db.Integer)
    sal = db.Column(db.Integer, nullable=False)
    comm = db.Column(db.Integer)
    dno = db.Column(db.Integer, db.ForeignKey('tb_dept.dno'))

    def to_simple_dict(self):
        return {
            'no': self.no,
            'name': self.name,
            'job': self.job,
            'sal': self.sal,
            'comm': self.comm,
            'dept': self.dept.name
        }

    def to_full_dict(self):
        return {
            'no': self.no,
            'name': self.name,
            'job': self.job,
            'mgr': self.mgr,
            'sal': self.sal,
            'comm': self.comm,
            'dept': self.dept.to_dict()
        }
